<template>
  <view class="chatwrap" :style="{ height: height+'px' }">
		<view class="header">
			<view class="iconfont icon-arrow-left-bold" @tap="back"></view>
			<view>{{trfNo}}</view>
			<view class="iconfont icon-danse_gongnengjihe" @tap="goUserList"></view>
		</view>
    <view class="wrap" @touchstart="hideBox" @click="hideBox">
			<view v-for="(item,index) in list" :key='index'>
				<view class="starttime">{{getMsgTime(item.senderTime,index)}}</view>
				<view class="chatbox" :class="item.userId==imGroupUser.userId?'right_chat':'left_chat'">
					<template>
						<view class="avator">{{getImg(item.userName)}}</view>
						<view class="chattext">
							<view class="nickname">{{item.userName}}</view>
							<view class="msg_con text" v-if="item.contentType=='text'" v-html='item.content'></view>
							<view v-else-if="item.contentType=='image'" class="msg_con chat_img">
								<img :src="item.content" alt="" @tap='previewImage(item.content)' ref='chatImg' v-if='item.content'>
							</view>
							<view v-else-if="item.contentType=='file'" class="msg_con chat_file" @tap="downFile(item)">
								<view class="file_name">{{item.content}}</view>
								<view class="iconfont icon-file-text-fill"></view>
							</view>
						</view>
					</template>
				</view>
			</view>
    </view>
    <form :report-submit="true" :style="{ bottom: bottom }">
      <view class="iptbox">
        <input type="text" name="input" ref='ipt' class="ipt" @input='textLenthChange' confirm-type='go' v-model="con" @confirm="sendmsg" @blur="keyblur" @focus="keyfocus" :cursor-spacing="cursorSpacing" :adjust-position="!isOnly">
				<view class="iconfont icon-Add" @tap="sendfunShow=true;smilesShow = false"></view>
      </view>
			<view class="sendfun_box" v-show="sendfunShow">
				<view class="sendfun_itemone" @tap="chooseImg('album')">
					<view class="iconfont icon-xiangce"></view>
					<view>相册</view>
				</view>
				<view class="sendfun_itemone" @tap="chooseImg('camera')">
					<view class="iconfont icon-weibiaoti1"></view>
					<view>拍摄</view>
				</view>
				<view class="sendfun_itemone" @tap="chooseFile()">
					<view class="iconfont icon-wenjian4"></view>
					<view>文件</view>
				</view>
			</view>
    </form>
  </view>
</template>

<script>
	import {toast} from '@/common/public.js'
	import {mkRslt,checkCh,add0,getRanNum} from '@/common/public.js'
  import {mixins} from '@/common/mixins.js'
  export default {
  	mixins:[mixins],
    data() {
      return {
        list:[],// 列表
				imGroupUser:'',//请求方信息
        con:'',// 发送的内容
        cursorSpacing:0, // 光标距离键盘的间隔
        kg:true,// 发送内容开关
        height:'',
				height1:'',
        bottom:0,
        input_height:277,
        isOnly:false,
				sendfunShow:false ,//输入框下方功能盒子显示和隐藏
				isLast:false,
				pages:{
					size:10,time:''
				},
				isFirst:true,
				init:true,
				beforeScrollHeight:0,
				trfNo:''
      }
    },
    created(){
      let height = uni.getSystemInfoSync().windowHeight 
      this.height = `${height}`
			this.height1 = height
      uni.getSystemInfo({
        success:e=>{
          if(e.platform=='ios'){
            this.input_height = 378
          }else{
            this.input_height = 277
          }
        }
      })
    },
    onLoad(options) {
      this.trfNo = options.trfNo || 'TRF1I00151'
			// oovO-5xBKxK7ozWIQMkVgJ7oQOPI
			this.weUserId = uni.getStorageSync('sgs_userId') || 'oovO-5xBKxK7ozWIQMkVgJ7oQOPI'
			if(this.weUserId) {
				this.$websocket.dispatch('webSocketInit',{trfNo:this.trfNo,weUserId:this.weUserId});
			} else {
				this.wxAuth()
			}
      uni.getSystemInfo({
				success: (res) => {
					this.cursorSpacing = Math.floor(res.windowWidth * 14 / 750) - 1
				}
      });
    },
		computed: {
		    //监听接收到的消息
			socketMsgs() {
				return this.$websocket.getters.socketMsgs
			},
			//监听是否连接和重连次数
			socketTask() {
				return {
					webSocketReconnectCount:this.$websocket.getters.webSocketReconnectCount,
					socketTask:this.$websocket.getters.socketTask,
				}
			}
		},
		watch: {
			socketTask(){
				if (!this.socketTask.socketTask && this.socketTask.webSocketReconnectCount>=2) {
					uni.showModal({
					    title: '提示',
					    content: '当前会话已关闭，请重新进入房间再试',
							showCancel:false,
					    success: (res) => {
								if (res.confirm) {
									this.$websocket.dispatch('webSocketClose');
									WeixinJSBridge.call('closeWindow');
								}
					    }
					});
				}
			},
			'socketMsgs': {
		    //处理接收到的消息
				handler: function() {
					let that = this
					let sMsg = that.socketMsgs
					 console.log('sMsg:'+sMsg.bstp,sMsg)
					if (sMsg.bstp == 1003) {
						// 用户列表更新
						this.imGroupUsers = sMsg.imGroupUsers
						uni.setStorageSync('imGroupUsers',this.imGroupUsers)
					} else if (sMsg.bstp == 1002) {
						// 收到群聊消息
						this.kg = true
						let imContent = sMsg.imContent
						for(let key in sMsg.imGroupUser) {
							if (key!='id') {
								imContent[key] = sMsg.imGroupUser[key]
							}
						}
						if (imContent.contentType == 'image') {
							that.downloadByCloudID(imContent.contentFileId,imContent.content,(url)=>{
								imContent.content = url
								this.list.push(imContent)
								this.con = ''
							})
						} else if(imContent.contentType == 'file'){
							let arr = imContent.content.split('/')
							imContent.content = arr[arr.length-1]
							this.list.push(imContent)
							this.con = ''
						} else {
							this.list.push(imContent)
							this.con = ''
						}
						if (imContent.userId == this.imGroupUser.userId) {
							this.$nextTick(()=>{
								if (imContent.contentType == 'image') {
									this.getImgLoadEd(()=>{
										setTimeout(()=>{
											this.sendfunShow = false
											this.setScrollTop()
										},1000)
									})
								} else {
									this.setScrollTop()
								}
							})
						}
					} else if (sMsg.bstp == 1004) {
						// 收到聊天记录
						uni.stopPullDownRefresh()
						
						if (sMsg.size == this.pages.size && sMsg.time == this.pages.time) {
							uni.showLoading({
								title:'加载中...'
							})
							let arr = sMsg.imContentList
							if (arr.length < 10) {
								that.isLast = true
							} else {
								that.isLast = false
							}
							arr.forEach(ele=>{
								let content = ele.content
								if (ele.contentType == 'image') {
									ele.content = ''
								}
								this.list.unshift(ele)
								if (ele.contentType == 'image') {
									that.downloadByCloudID(ele.contentFileId,content,(url)=>{
										ele.content = url
										if (this.isFirst) {
											this.$nextTick(()=>{
												this.getImgLoadEd(()=>{
													setTimeout(()=>{
														this.setScrollTop()
													},1000)
												})
											})
										}
									})
								} else if(ele.contentType == 'file'){
									let arr = ele.content.split('/')
									ele.content = arr[arr.length-1]
									if (this.isFirst) {
										this.setScrollTop()
									}
								} else {
									if (this.isFirst) {
										this.setScrollTop()
									}
								}
							})
							if (!this.isFirst) {
								this.$nextTick(()=>{
									this.getImgLoadEd(()=>{
										setTimeout(()=>{
											let query = uni.createSelectorQuery().in(this)
											query.select('.wrap').boundingClientRect((res)=>{
												let top = res.height - this.beforeScrollHeight
												uni.pageScrollTo({
													duration:0,
													scrollTop:top
												})
												uni.hideLoading()
											}).exec()
										},1000)
									})
								})
							} else {
								uni.hideLoading()
							}
						}
					} else if (sMsg.bstp == 1005) {
						// 收到当前用户信息
						this.imGroupUser = sMsg.imGroupUser
						if (this.init) {
							this.list = []
							this.pages.time = new Date().getTime()
							this.isFirst = true
							this.sendGetListMsg()
							this.init = false
						}
					}
		    }
			}
		},
    // 下拉刷新
    onPullDownRefresh() {
			if (this.isLast || !this.imGroupUser) return
			let query = uni.createSelectorQuery().in(this)
			query.select('.wrap').boundingClientRect((res)=>{
				this.beforeScrollHeight = res.height
			}).exec()
      setTimeout(() => {
				this.pages.time = this.list[0].senderTime
				this.isFirst = false
        this.sendGetListMsg()
      }, 800);
    },
    methods: {
			// 获取聊天内容
			sendGetListMsg() {
				this.$websocket.dispatch('webSocketSend',{
					bstp:1004,
					time:this.pages.time,
					size:this.pages.size
				});
			},
			// 发送聊天内容
			sendMsg(msg,file_type,contentFileId) {
				this.$websocket.dispatch('webSocketSend',{
					bstp:1002,
					contentType:file_type,
					content:msg,
					contentFileId:contentFileId
				});
			},
      // 发送消息
      sendmsg() {
        if (!this.kg) return
        let con = this.con
        if (con == ''){
          this.setScrollTop()
        } else {
          this.kg = false;
					this.sendMsg(con,'text','')
        }
      },
			chooseImg(sourceType) {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: [sourceType], //从相册选择
					success: (res) => {
						this.upFile(res.tempFilePaths[0],'image')
					}
				});
			},
			chooseFile() {
				uni.chooseFile({
					count: 6, //默认100
					extension:['.docx','.doc','.pdf','.xlsx'],
						success: (res) => {
							this.upFile(res.tempFilePaths[0],'file')
						}
				});
			},
			upFile(url,type) {
				uni.uploadFile({
					url: this.baseUrl+'/api/sgsapi/FrameWorkApi/file/doUpload?systemID=1',
					filePath: url,
					name: 'file',
					success: (uploadFileRes) => {
						if (uploadFileRes.data) {
							let data = JSON.parse(uploadFileRes.data).data
							if (data.length>0) {
								this.sendMsg(data[0].path,type,data[0].cloudID)
							}
						}
					}
				});
			},
			downloadByCloudID(cloudId,fileName,callback) {
				let url = ''
				let param = {
					systemID:1,
					networkType:2,
					hash:new Date().getTime(),
					cloudID:cloudId
				}
				this.$api.downloadByCloudID(param).then(res=>{
					if (res) {
						let link = res.replace(/\s*/g,'')
						// let fileUrl = encodeURIComponent(link)
						// url = this.baseUrl+'/api/sgs-mart/afl/trf/fileDownload?fileUrl='+fileUrl+'&fileUrlName='+fileName
						callback&&callback(link)
					} else {
						toast(res.msg)
					}
				})
			},
			// 根据名字返回头像
			getImg(str) {
				if (/^[a-zA-Z]+/g.test(str)) {
					let arr = str.split(' ')
					let name = ''
					arr.forEach(n=>{
						name+=n.slice(0,1).toUpperCase()
					})
					return name
				}
				var arrResult = new Array();
				for(var i=0,len=str.length;i<len;i++){
					var ch = str.charAt(i);
					arrResult.push(checkCh(ch));
				}
				let arr = mkRslt(arrResult)
				return arr.length>0?arr[0]:'';
			},
			back() {
				uni.navigateBack({
					
				})
			},
			goUserList() {
				uni.navigateTo({
					url:'/pages/userList/userList'
				})
			},
			hideBox() {
				this.sendfunShow=false
				this.smilesShow = false
			},
      // input失去焦点事件
      keyblur() {
        this.height = this.height1
        if(this.isOnly){
          this.bottom = 0
        }
        if (this.con != '') return
        this.setScrollTop()
      },
      // input获取焦点事件
      keyfocus(e) {
				this.sendfunShow = false
				this.smilesShow = false
        if(this.isOnly){
          let height = uni.getSystemInfoSync().windowHeight
					let h = e.detail.height
          this.height = `${height - h}`
          this.bottom = `${h}px`
          this.input_height = h
        }
      },
			previewImage(img) {
				uni.previewImage({
					urls: [img],
					itemList: ['发送给微信好友', '保存图片', '收藏'],
				})
			},
			downFile(item) {
				this.downloadByCloudID(item.contentFileId,item.content,(url)=>{
					window.top.location.href=window.location.origin+window.location.pathname+"/hybrid/html/download.html?fileurl="+encodeURIComponent(url);
				})
				// let fileUrl = encodeURIComponent(item.content)
				// let url = this.baseUrl+'/api/sgs-mart/afl/trf/fileDownload?fileUrl='+fileUrl+'&fileUrlName='+item.contentFileId
				// uni.downloadFile({
				//     url: url, //仅为示例，并非真实的资源
				//     success: (res) => {
				// 		if (res.statusCode === 200) {
				// 			toast('下载成功')
				// 		}
				//    },
				// 	fail:()=>{
				// 		uni.hideLoading()
				// 	}
				// });
			},
			getImgLoadEd(callback) {
				this.$nextTick(()=>{
					// 查询容器下所有图片
					let images = this.$refs.chatImg
					if (!images || images.length==0) {
						callback && callback();
					} else {
						let count = 0
						let arrs = Array.prototype.slice.call(images)
						arrs.map(node => {
								let loadImg = new Image();
								loadImg.src = node.src;
								loadImg.onload = () => {
									count++
									if (arrs.length == count) {
										callback && callback();
									}
								}
								loadImg.onerror = () => {
									count++
									if (arrs.length == count) {
										callback && callback();
									}
								}
						});
					}
				})
			},
      // 发送完消息后滚动到最底部
      setScrollTop() {
				this.$nextTick(()=>{
					let query = uni.createSelectorQuery().in(this)
					let height = uni.getSystemInfoSync().windowHeight
					query.select('.wrap').boundingClientRect((res)=>{
						uni.pageScrollTo({
							duration:0,
							scrollTop:res.height
						})
						if(res.height<(height-this.input_height)){
							this.isOnly=true
						}
					}).exec()
				})
      },
			//根据两个时间对比判断是否显示时间
			getMsgTime(time,index){
				if (index == 0) return this.getTimeDate(time)
				let time1 = this.list[index-1].senderTime
				if (time - time1 > 5*60*1000) return this.getTimeDate(time)
			},
			// 根据时间戳转日期
			getTimeDate(shijianchuo) {
				var time = new Date(shijianchuo);
				var y = time.getFullYear();
				var m = time.getMonth()+1;
				var d = time.getDate();
				var h = time.getHours();
				var mm = time.getMinutes();
				var s = time.getSeconds();
				var time1 = new Date()
				var y1 = time1.getFullYear();
				var m1 = time1.getMonth()+1;
				var d1 = time1.getDate();
				if (y1 - y >= 1) {
					return y+'年'+add0(m)+'月'+add0(d)+'日 '+add0(h)+':'+add0(mm);
				} else if (m1 - m >= 1 || d1 - d > 1) {
					let am = ''
					if (h < 12) {
						am = '上午'
					} else if (h < 18) {
						am = '下午'
					} else {
						am = '晚上'
					}
					return add0(m)+'月'+add0(d)+'日 '+am+add0(h)+':'+add0(mm);
				} else if (d1 - d == 1) {
					return '昨天 '+add0(h)+':'+add0(mm);
				} else {
					return add0(h)+':'+add0(mm);
				}
			},
			// 监听输入字数多少给提示
			textLenthChange() {
				if (this.con.length > 500) {
					uni.showToast({
						title:'最多可输入500字！',
						icon:'none'
					})
					this.con = this.con.slice(0,500)
				}
			},
    },
  }
</script>
<style lang="stylus" scoped>
	.chatwrap
		background-color #e4e4e4
		.header
			position fixed
			left 0
			top 0
			height 88rpx
			width 100%
			background-color #f8f8f8
			text-align center
			line-height 88rpx
			border-bottom 2rpx solid #eee
			z-index 999
			.icon-arrow-left-bold
				position absolute
				left 0
				top 0
				padding:0 20rpx
				font-size 40rpx
			.icon-danse_gongnengjihe
				position absolute
				right 0
				top 0
				padding:0 20rpx
				font-size 40rpx
	.wrap
		padding 120rpx 30rpx 100rpx 30rpx
		box-sizing border-box
		background-color #e4e4e4
		.starttime
			font-size 24rpx
			color #9E9E9E
			margin 30rpx 0
			text-align center
		.chatbox
			display flex
			align-items flex-start
			margin-bottom 68rpx
			&.right_chat
				flex-direction row-reverse
				.chattext
					text-align right
					.text
						// border:1px solid #ff6600
						background #ff6600
						color #fff
						&::before
							display: inline-block;
							content: " ";
							height: 18rpx;
							width: 18rpx;
							background #ff6600
							border-width: 2rpx 2rpx 0 0;
							border-color: #ff6600
							border-style: solid;
							transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
							position: absolute;
							top: 36rpx;
							right: -10rpx;
							margin-top: -9rpx;
				.avator
					margin-left 28rpx
			&.left_chat
				.avator
					margin-right 28rpx
				.text
					background #fff
					&::before
						display: inline-block;
						content: " ";
						height: 18rpx;
						width: 18rpx;
						background #fff
						border-width:0 0 2rpx 2rpx;
						border-color: #fff
						border-style: solid;
						transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
						position: absolute;
						top: 36rpx;
						left: -10rpx;
						margin-top: -9rpx;
			.avator
				width 80rpx
				height 80rpx
				border-radius 20rpx
				background-color #fff
				text-align center
				line-height 80rpx
				color #FF6600
				font-size 30rpx
				margin-top 30rpx
			.chattext
				flex 1
				min-width 0
				.text
					max-width 80%
					position relative
					display inline-block
					border-radius 8rpx
					padding 18rpx 40rpx 18rpx 32rpx
					font-size 30rpx
					color #333
					text-align left
					word-wrap break-word
					word-break break-all
					&.yuyin_box
						font-size 24rpx
						.iconfont
							font-size 24rpx
							margin-left 4rpx
				.chat_img
					width 100%
					line-height 0
					img
						display inline-block
						max-width 50%
						max-height 400rpx
				.chat_file
					border 2rpx solid #EEEEEE
					background-color #fff
					font-size 26rpx
					padding 20rpx
					text-align left
					display flex
					align-items flex-start
					justify-content space-between
					.iconfont
						color #999
						font-size 40rpx
		.nickname
			font-size 28rpx
			line-height 80rpx
		.defaultbox
			text-align center
			margin-bottom 20px
			text
				font-size 28rpx
				padding 4rpx 10rpx
				background-color #ddd
				color #fff
				border-radius 8rpx
	form
		position fixed
		left 0
		width 100%
		background #eee
		border-top 2rpx solid #ddd
		.iptbox
			width 100%
			padding 16rpx 30rpx 30rpx
			box-sizing border-box
			display flex
			align-items center
			border-bottom 2rpx solid #eee
			.iconfont
				font-size 48rpx
				color #222
			.ipt
				flex 1
				margin 0 30rpx 0 0
				height 70rpx
				min-width 0
				background #FFF
				padding-left 20rpx
				box-sizing border-box
				border-radius 8rpx
				&.say_btn
					text-align center
					font-size 28rpx
					line-height 70rpx
				&.cur
					background-color #eee
		.sendfun_box
			display flex
			padding 50rpx 40rpx
			.sendfun_itemone
				width 100rpx
				margin 0 80rpx 40rpx 0
				font-size 24rpx
				color #777
				text-align center
				.iconfont
					width 100rpx
					height 100rpx
					background-color #fff
					text-align center
					line-height 100rpx
					font-size 48rpx
					color #222
					margin-bottom 10rpx
					border-radius 20rpx
</style>
